<script setup lang='ts'>
import { CodeService } from '@/api/public/util'
import { UpdateUserPasswordService } from '@/api/User/user'
import bus from '@/utils/bus'

const formModel = ref({
  email: '',
  code: '',
  password: '',
  repassword: '',
  type: 'edit',
})
const formRef = ref()
const rules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱', trigger: ['blur', 'change'] },
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '请输入6位验证码', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
  ],
  repassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value !== formModel.value.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
}
const emits = defineEmits(['handleClose'])

const disabled2 = ref(false)
const yz = ref({
  total: 60,
  curry: 60,
  timer: null as number | null,
})
const onSend = () => {
  // 禁用按钮，确保快速点击时不会重复触发
  disabled2.value = true

  try {
    // 在此处，如果验证不通过，error 将会是 false
    formRef.value.validateField('email', async (error: boolean) => {
      if (!error) {
        // 如果邮箱验证失败，提示用户输入邮箱
        ElMessage.error('请输入邮箱地址')
      } else {
        // 如果有定时器正在运行，防止重复点击
        if (yz.value.timer) {
          ElMessage.info('验证码正在发送，请稍后再试')
          return
        }

        // 如果倒计时已经结束（curry == total），就重新发送验证码
        if (yz.value.curry === yz.value.total) {
          // 调用验证码服务
          await CodeService(formModel.value.email,formModel.value.type)
          ElMessage.success('验证码已发送，十分钟以内有效, 请注意查收')

          // 开启定时器，倒计时
          yz.value.timer = setInterval(() => {
            yz.value.curry--
            if (yz.value.curry <= 0) {
              // 倒计时结束，清除定时器
              clearInterval(yz.value.timer!)
              yz.value.timer = null
              yz.value.curry = yz.value.total
            }
          }, 1000)
        } else {
          // 如果定时器还在运行，提示用户稍后再试
          ElMessage.info(`请稍等，验证码将在 ${yz.value.curry} 秒后可重新发送`)
        }
      }
    })
  } finally {
    // 在执行完成后恢复按钮状态，避免点击间隔过快
    setTimeout(() => {
      disabled2.value = false
    }, 1000) // 这里设置了 1 秒的延迟，避免点击过快
  }
}

const disabled = ref(false)
const onSubmit = async () => {
  await formRef.value.validate()
  disabled.value = true
  try {
    await UpdateUserPasswordService({
      email: formModel.value.email,
      code: formModel.value.code,
      password: formModel.value.password,
      type: formModel.value.type,
    })
    bus.emit('userChange')
    emits('handleClose')
  } catch (err) {
    ElMessage.error('修改失败')
  } finally {
    disabled.value = false
    close()
  }
}

const close = () => {
  formRef.value.resetFields()
  clearInterval(yz.value.timer!)
  yz.value.timer = null
  yz.value.curry = yz.value.total
}
const open = (email: string) => {
  formModel.value.email = email
}

defineExpose({
  close,
  open,
})
</script>
<template>
  <div class="user-setting">
    <el-form autocomplete="off" :model="formModel" :rules="rules" ref="formRef" label-width="80px">
      <el-form-item label="邮箱" prop="email">
        <el-input disabled v-model="formModel.email" placeholder="请输入邮箱">
          <template #append>
            <el-button :disabled="disabled2" @click="onSend">{{
              yz.total === yz.curry ? '获取验证码' : yz.curry + 's后重新发送'
            }}</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input v-model="formModel.code" placeholder="请输入验证码"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="formModel.password"
          show-password
          type="password"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="repassword">
        <el-input
          v-model="formModel.repassword"
          show-password
          type="password"
          placeholder="请确认密码"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button :disabled="disabled" @click="onSubmit" type="primary" style="width: 100%"
          >修改</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<style scoped lang='scss'>
</style>